from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
import os
import sqlite3

db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 确保上传文件夹存在
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    
    db.init_app(app)
    migrate.init_app(app, db)
    
    from app.routes import main
    app.register_blueprint(main)
    
    # 检查数据库文件是否存在
    db_path = os.path.join(os.path.dirname(app.instance_path), 'instance', 'words.db')
    
    with app.app_context():
        if not os.path.exists(db_path):
            # 只在数据库不存在时创建表
            db.create_all()
            print("Database created.")
        else:
            # 检查是否需要添加新列
            try:
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                
                # 获取现有的列
                cursor.execute('PRAGMA table_info(word)')
                columns = [column[1] for column in cursor.fetchall()]
                
                # 检查并添加缺失的列
                if 'translation' not in columns:
                    cursor.execute('ALTER TABLE word ADD COLUMN translation TEXT')
                if 'next_review_date' not in columns:
                    cursor.execute('ALTER TABLE word ADD COLUMN next_review_date DATETIME')
                if 'mastered' not in columns:
                    cursor.execute('ALTER TABLE word ADD COLUMN mastered BOOLEAN DEFAULT FALSE')
                
                conn.commit()
                conn.close()
                print("Database schema updated if needed.")
            except Exception as e:
                print(f"Error checking/updating database schema: {e}")
    
    @app.after_request
    def add_header(response):
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
        response.headers['Pragma'] = 'no-cache'
        response.headers['Expires'] = '-1'
        return response
    
    return app 